#!/bin/sh

# 重启spring boot项目

# 这里切记别用-ex，用了当应用未启动时会挂
set -x

if [ $# -lt 4 ]; then
        echo "deploy_spring_boot_script jobName jmsRemotePort(-1 not set) parentProjectName [serverPort](optional)"
        exit -1
fi

JOB_NAME=$1
JMX_REMOTE_PORT=$2
PARENT_PROJECT_NAME=$3
PROJECT_NAME=$4
APP_HOME=/home/www/server/${PARENT_PROJECT_NAME}/${PROJECT_NAME}/

ORIGINAL_JAR_HOME=${JENKINS_HOME}/workspace/${JOB_NAME}/target/${PROJECT_NAME}-[0-9]*\.jar
if [ ! -d "${JENKINS_HOME}/workspace/${JOB_NAME}/src" ]; then
        ORIGINAL_JAR_HOME=${JENKINS_HOME}/workspace/${JOB_NAME}/*/target/${PROJECT_NAME}-[0-9]*\.jar
fi

if [ ! -d "${APP_HOME}" ]; then
        mkdir -p  ${APP_HOME}
fi

rm -rf ${APP_HOME}*

cp $ORIGINAL_JAR_HOME $APP_HOME
APP=${APP_HOME}${PROJECT_NAME}-[0-9]*\.jar
chmod +x ${APP}
psef=`ps -ef | grep "${PROJECT_NAME}\-[0-9]" | grep 'jar'`
echo "${psef}"
if [ -n "$psef" ]; then
        pid=`echo ${psef}| awk '{print $2}' | sed -n '1p'`
        echo $pid
        kill -9 $pid
fi

if [ "$JMX_REMOTE_PORT" -eq "-1" ]; then
        cmd="nohup java -jar ${APP} --spring.profiles.active=test"
else
        cmd="nohup java -Dcom.sun.management.jmxremote.port=${JMX_REMOTE_PORT}"
        cmd="${cmd} -Dcom.sun.management.jmxremote.ssl=false "
        cmd="${cmd} -Dcom.sun.management.jmxremote.authenticate=false "
        cmd="${cmd} -Dcom.sun.management.jmxremote.local.only=false"
        cmd="${cmd} -Djava.rmi.server.hostname=192.168.1.113 -jar ${APP}"
        cmd="${cmd} --spring.profiles.active=test"
fi

if [ $# == 5 ]; then
        cmd="${cmd} --server.port=$5"
fi

cmd="${cmd} > ${APP_HOME}${PROJECT_NAME}.log 2>&1 &"

eval $cmd
